package com.servlet.download;

import cn.itcast.web.utils.DownLoadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/servlet02")
public class Servlet02 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        String filename = req.getParameter("filename");
        //2.关联字节流加载进内存
        //2.1获取真实路径
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);
        FileInputStream fis=new FileInputStream(realPath);
        //3.设置响应头(有什么作用?)
        String mimeType = servletContext.getMimeType(filename);
        resp.setHeader("content-type",mimeType);

        //解决中文乱码,弹出下载框
        String agent = req.getHeader("user-agent");
        filename = DownLoadUtils.getFileName(agent, filename);
        resp.setHeader("content-disposition","attachment;filename="+filename);

        //4.将输入流数据写入响应输出流中去
        ServletOutputStream os = resp.getOutputStream();
        byte[] bys=new byte[1024*8];
        int len;
        while ((len=fis.read(bys))!=-1){
            os.write(bys,0,len);
        }
        fis.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
